home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / python2.6 / dist-packages / pkg_resources.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  87.4 KB  |  2,549 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Package resource API
  5. --------------------
  6.  
  7. A resource is a logical file contained within a package, or a logical
  8. subdirectory thereof.  The package resource API expects resource names
  9. to have their path parts separated with ``/``, *not* whatever the local
  10. path separator is.  Do not use os.path operations to manipulate resource
  11. names being passed into the API.
  12.  
  13. The package resource API is designed to work with normal filesystem packages,
  14. .egg files, and unpacked .egg files.  It can also work in a limited way with
  15. .zip files and with custom PEP 302 loaders that support the ``get_data()``
  16. method.
  17. '''
  18. import sys
  19. import os
  20. import zipimport
  21. import time
  22. import re
  23. import imp
  24. import new
  25.  
  26. try:
  27.     frozenset
  28. except NameError:
  29.     from sets import ImmutableSet as frozenset
  30.  
  31. from os import utime, rename, unlink
  32. from os import open as os_open
  33.  
  34. def get_supported_platform():
  35.     """Return this platform's maximum compatible version.
  36.  
  37.     distutils.util.get_platform() normally reports the minimum version
  38.     of Mac OS X that would be required to *use* extensions produced by
  39.     distutils.  But what we want when checking compatibility is to know the
  40.     version of Mac OS X that we are *running*.  To allow usage of packages that
  41.     explicitly require a newer version of Mac OS X, we must also know the
  42.     current version of the OS.
  43.  
  44.     If this condition occurs for any other platform with a version in its
  45.     platform strings, this function should be extended accordingly.
  46.     """
  47.     plat = get_build_platform()
  48.     m = macosVersionString.match(plat)
  49.     if m is not None and sys.platform == 'darwin':
  50.         
  51.         try:
  52.             plat = 'macosx-%s-%s' % ('.'.join(_macosx_vers()[:2]), m.group(3))
  53.         except ValueError:
  54.             pass
  55.         except:
  56.             None<EXCEPTION MATCH>ValueError
  57.         
  58.  
  59.     None<EXCEPTION MATCH>ValueError
  60.     return plat
  61.  
  62. __all__ = [
  63.     'require',
  64.     'run_script',
  65.     'get_provider',
  66.     'get_distribution',
  67.     'load_entry_point',
  68.     'get_entry_map',
  69.     'get_entry_info',
  70.     'iter_entry_points',
  71.     'resource_string',
  72.     'resource_stream',
  73.     'resource_filename',
  74.     'resource_listdir',
  75.     'resource_exists',
  76.     'resource_isdir',
  77.     'declare_namespace',
  78.     'working_set',
  79.     'add_activation_listener',
  80.     'find_distributions',
  81.     'set_extraction_path',
  82.     'cleanup_resources',
  83.     'get_default_cache',
  84.     'Environment',
  85.     'WorkingSet',
  86.     'ResourceManager',
  87.     'Distribution',
  88.     'Requirement',
  89.     'EntryPoint',
  90.     'ResolutionError',
  91.     'VersionConflict',
  92.     'DistributionNotFound',
  93.     'UnknownExtra',
  94.     'ExtractionError',
  95.     'parse_requirements',
  96.     'parse_version',
  97.     'safe_name',
  98.     'safe_version',
  99.     'get_platform',
  100.     'compatible_platforms',
  101.     'yield_lines',
  102.     'split_sections',
  103.     'safe_extra',
  104.     'to_filename',
  105.     'ensure_directory',
  106.     'normalize_path',
  107.     'EGG_DIST',
  108.     'BINARY_DIST',
  109.     'SOURCE_DIST',
  110.     'CHECKOUT_DIST',
  111.     'DEVELOP_DIST',
  112.     'IMetadataProvider',
  113.     'IResourceProvider',
  114.     'FileMetadata',
  115.     'PathMetadata',
  116.     'EggMetadata',
  117.     'EmptyProvider',
  118.     'empty_provider',
  119.     'NullProvider',
  120.     'EggProvider',
  121.     'DefaultProvider',
  122.     'ZipProvider',
  123.     'register_finder',
  124.     'register_namespace_handler',
  125.     'register_loader_type',
  126.     'fixup_namespace_packages',
  127.     'get_importer',
  128.     'run_main',
  129.     'AvailableDistributions']
  130.  
  131. class ResolutionError(Exception):
  132.     '''Abstract base for dependency resolution errors'''
  133.     
  134.     def __repr__(self):
  135.         return self.__class__.__name__ + repr(self.args)
  136.  
  137.  
  138.  
  139. class VersionConflict(ResolutionError):
  140.     '''An already-installed version conflicts with the requested version'''
  141.     pass
  142.  
  143.  
  144. class DistributionNotFound(ResolutionError):
  145.     '''A requested distribution was not found'''
  146.     pass
  147.  
  148.  
  149. class UnknownExtra(ResolutionError):
  150.     '''Distribution doesn\'t have an "extra feature" of the given name'''
  151.     pass
  152.  
  153. _provider_factories = { }
  154. PY_MAJOR = sys.version[:3]
  155. EGG_DIST = 3
  156. BINARY_DIST = 2
  157. SOURCE_DIST = 1
  158. CHECKOUT_DIST = 0
  159. DEVELOP_DIST = -1
  160.  
  161. def register_loader_type(loader_type, provider_factory):
  162.     '''Register `provider_factory` to make providers for `loader_type`
  163.  
  164.     `loader_type` is the type or class of a PEP 302 ``module.__loader__``,
  165.     and `provider_factory` is a function that, passed a *module* object,
  166.     returns an ``IResourceProvider`` for that module.
  167.     '''
  168.     _provider_factories[loader_type] = provider_factory
  169.  
  170.  
  171. def get_provider(moduleOrReq):
  172.     '''Return an IResourceProvider for the named module or requirement'''
  173.     if isinstance(moduleOrReq, Requirement):
  174.         if not working_set.find(moduleOrReq):
  175.             pass
  176.         return require(str(moduleOrReq))[0]
  177.     
  178.     try:
  179.         module = sys.modules[moduleOrReq]
  180.     except KeyError:
  181.         isinstance(moduleOrReq, Requirement)
  182.         isinstance(moduleOrReq, Requirement)
  183.         __import__(moduleOrReq)
  184.         module = sys.modules[moduleOrReq]
  185.     except:
  186.         isinstance(moduleOrReq, Requirement)
  187.  
  188.     loader = getattr(module, '__loader__', None)
  189.     return _find_adapter(_provider_factories, loader)(module)
  190.  
  191.  
  192. def _macosx_vers(_cache = []):
  193.     if not _cache:
  194.         info = os.popen('/usr/bin/sw_vers').read().splitlines()
  195.         for line in info:
  196.             (key, value) = line.split(None, 1)
  197.             if key == 'ProductVersion:':
  198.                 _cache.append(value.strip().split('.'))
  199.                 break
  200.                 continue
  201.         else:
  202.             raise ValueError, 'What?!'
  203.     return _cache[0]
  204.  
  205.  
  206. def _macosx_arch(machine):
  207.     return {
  208.         'PowerPC': 'ppc',
  209.         'Power_Macintosh': 'ppc' }.get(machine, machine)
  210.  
  211.  
  212. def get_build_platform():
  213.     """Return this platform's string for platform-specific distributions
  214.  
  215.     XXX Currently this is the same as ``distutils.util.get_platform()``, but it
  216.     needs some hacks for Linux and Mac OS X.
  217.     """
  218.     get_platform = get_platform
  219.     import distutils.util
  220.     plat = get_platform()
  221.     if sys.platform == 'darwin' and not plat.startswith('macosx-'):
  222.         
  223.         try:
  224.             version = _macosx_vers()
  225.             machine = os.uname()[4].replace(' ', '_')
  226.             return 'macosx-%d.%d-%s' % (int(version[0]), int(version[1]), _macosx_arch(machine))
  227.         except ValueError:
  228.             pass
  229.         except:
  230.             None<EXCEPTION MATCH>ValueError
  231.         
  232.  
  233.     None<EXCEPTION MATCH>ValueError
  234.     return plat
  235.  
  236. macosVersionString = re.compile('macosx-(\\d+)\\.(\\d+)-(.*)')
  237. darwinVersionString = re.compile('darwin-(\\d+)\\.(\\d+)\\.(\\d+)-(.*)')
  238. get_platform = get_build_platform
  239.  
  240. def compatible_platforms(provided, required):
  241.     '''Can code for the `provided` platform run on the `required` platform?
  242.  
  243.     Returns true if either platform is ``None``, or the platforms are equal.
  244.  
  245.     XXX Needs compatibility checks for Linux and other unixy OSes.
  246.     '''
  247.     if provided is None and required is None or provided == required:
  248.         return True
  249.     reqMac = macosVersionString.match(required)
  250.     if reqMac:
  251.         provMac = macosVersionString.match(provided)
  252.         if not provMac:
  253.             provDarwin = darwinVersionString.match(provided)
  254.             return False
  255.         if provMac.group(1) != reqMac.group(1) or provMac.group(3) != reqMac.group(3):
  256.             return False
  257.         if int(provMac.group(2)) > int(reqMac.group(2)):
  258.             return False
  259.         return True
  260.     return False
  261.  
  262.  
  263. def run_script(dist_spec, script_name):
  264.     '''Locate distribution `dist_spec` and run its `script_name` script'''
  265.     ns = sys._getframe(1).f_globals
  266.     name = ns['__name__']
  267.     ns.clear()
  268.     ns['__name__'] = name
  269.     require(dist_spec)[0].run_script(script_name, ns)
  270.  
  271. run_main = run_script
  272.  
  273. def get_distribution(dist):
  274.     '''Return a current distribution object for a Requirement or string'''
  275.     if isinstance(dist, basestring):
  276.         dist = Requirement.parse(dist)
  277.     
  278.     if isinstance(dist, Requirement):
  279.         dist = get_provider(dist)
  280.     
  281.     if not isinstance(dist, Distribution):
  282.         raise TypeError('Expected string, Requirement, or Distribution', dist)
  283.     isinstance(dist, Distribution)
  284.     return dist
  285.  
  286.  
  287. def load_entry_point(dist, group, name):
  288.     '''Return `name` entry point of `group` for `dist` or raise ImportError'''
  289.     return get_distribution(dist).load_entry_point(group, name)
  290.  
  291.  
  292. def get_entry_map(dist, group = None):
  293.     '''Return the entry point map for `group`, or the full entry map'''
  294.     return get_distribution(dist).get_entry_map(group)
  295.  
  296.  
  297. def get_entry_info(dist, group, name):
  298.     '''Return the EntryPoint object for `group`+`name`, or ``None``'''
  299.     return get_distribution(dist).get_entry_info(group, name)
  300.  
  301.  
  302. class IMetadataProvider:
  303.     
  304.     def has_metadata(name):
  305.         """Does the package's distribution contain the named metadata?"""
  306.         pass
  307.  
  308.     
  309.     def get_metadata(name):
  310.         '''The named metadata resource as a string'''
  311.         pass
  312.  
  313.     
  314.     def get_metadata_lines(name):
  315.         '''Yield named metadata resource as list of non-blank non-comment lines
  316.  
  317.        Leading and trailing whitespace is stripped from each line, and lines
  318.        with ``#`` as the first non-blank character are omitted.'''
  319.         pass
  320.  
  321.     
  322.     def metadata_isdir(name):
  323.         '''Is the named metadata a directory?  (like ``os.path.isdir()``)'''
  324.         pass
  325.  
  326.     
  327.     def metadata_listdir(name):
  328.         '''List of metadata names in the directory (like ``os.listdir()``)'''
  329.         pass
  330.  
  331.     
  332.     def run_script(script_name, namespace):
  333.         '''Execute the named script in the supplied namespace dictionary'''
  334.         pass
  335.  
  336.  
  337.  
  338. class IResourceProvider(IMetadataProvider):
  339.     '''An object that provides access to package resources'''
  340.     
  341.     def get_resource_filename(manager, resource_name):
  342.         '''Return a true filesystem path for `resource_name`
  343.  
  344.         `manager` must be an ``IResourceManager``'''
  345.         pass
  346.  
  347.     
  348.     def get_resource_stream(manager, resource_name):
  349.         '''Return a readable file-like object for `resource_name`
  350.  
  351.         `manager` must be an ``IResourceManager``'''
  352.         pass
  353.  
  354.     
  355.     def get_resource_string(manager, resource_name):
  356.         '''Return a string containing the contents of `resource_name`
  357.  
  358.         `manager` must be an ``IResourceManager``'''
  359.         pass
  360.  
  361.     
  362.     def has_resource(resource_name):
  363.         '''Does the package contain the named resource?'''
  364.         pass
  365.  
  366.     
  367.     def resource_isdir(resource_name):
  368.         '''Is the named resource a directory?  (like ``os.path.isdir()``)'''
  369.         pass
  370.  
  371.     
  372.     def resource_listdir(resource_name):
  373.         '''List of resource names in the directory (like ``os.listdir()``)'''
  374.         pass
  375.  
  376.  
  377.  
  378. class WorkingSet(object):
  379.     '''A collection of active distributions on sys.path (or a similar list)'''
  380.     
  381.     def __init__(self, entries = None):
  382.         '''Create working set from list of path entries (default=sys.path)'''
  383.         self.entries = []
  384.         self.entry_keys = { }
  385.         self.by_key = { }
  386.         self.callbacks = []
  387.         if entries is None:
  388.             entries = sys.path
  389.         
  390.         for entry in entries:
  391.             self.add_entry(entry)
  392.         
  393.  
  394.     
  395.     def add_entry(self, entry):
  396.         '''Add a path item to ``.entries``, finding any distributions on it
  397.  
  398.         ``find_distributions(entry,False)`` is used to find distributions
  399.         corresponding to the path entry, and they are added.  `entry` is
  400.         always appended to ``.entries``, even if it is already present.
  401.         (This is because ``sys.path`` can contain the same value more than
  402.         once, and the ``.entries`` of the ``sys.path`` WorkingSet should always
  403.         equal ``sys.path``.)
  404.         '''
  405.         self.entry_keys.setdefault(entry, [])
  406.         self.entries.append(entry)
  407.         for dist in find_distributions(entry, True):
  408.             self.add(dist, entry, False)
  409.         
  410.  
  411.     
  412.     def __contains__(self, dist):
  413.         '''True if `dist` is the active distribution for its project'''
  414.         return self.by_key.get(dist.key) == dist
  415.  
  416.     
  417.     def find(self, req):
  418.         '''Find a distribution matching requirement `req`
  419.  
  420.         If there is an active distribution for the requested project, this
  421.         returns it as long as it meets the version requirement specified by
  422.         `req`.  But, if there is an active distribution for the project and it
  423.         does *not* meet the `req` requirement, ``VersionConflict`` is raised.
  424.         If there is no active distribution for the requested project, ``None``
  425.         is returned.
  426.         '''
  427.         dist = self.by_key.get(req.key)
  428.         if dist is not None and dist not in req:
  429.             raise VersionConflict(dist, req)
  430.         dist not in req
  431.         return dist
  432.  
  433.     
  434.     def iter_entry_points(self, group, name = None):
  435.         '''Yield entry point objects from `group` matching `name`
  436.  
  437.         If `name` is None, yields all entry points in `group` from all
  438.         distributions in the working set, otherwise only ones matching
  439.         both `group` and `name` are yielded (in distribution order).
  440.         '''
  441.         for dist in self:
  442.             entries = dist.get_entry_map(group)
  443.             if name is None:
  444.                 for ep in entries.values():
  445.                     yield ep
  446.                 
  447.             if name in entries:
  448.                 yield entries[name]
  449.                 continue
  450.         
  451.  
  452.     
  453.     def run_script(self, requires, script_name):
  454.         '''Locate distribution for `requires` and run `script_name` script'''
  455.         ns = sys._getframe(1).f_globals
  456.         name = ns['__name__']
  457.         ns.clear()
  458.         ns['__name__'] = name
  459.         self.require(requires)[0].run_script(script_name, ns)
  460.  
  461.     
  462.     def __iter__(self):
  463.         """Yield distributions for non-duplicate projects in the working set
  464.  
  465.         The yield order is the order in which the items' path entries were
  466.         added to the working set.
  467.         """
  468.         seen = { }
  469.         for item in self.entries:
  470.             for key in self.entry_keys[item]:
  471.                 if key not in seen:
  472.                     seen[key] = 1
  473.                     yield self.by_key[key]
  474.                     continue
  475.             
  476.         
  477.  
  478.     
  479.     def add(self, dist, entry = None, insert = True):
  480.         """Add `dist` to working set, associated with `entry`
  481.  
  482.         If `entry` is unspecified, it defaults to the ``.location`` of `dist`.
  483.         On exit from this routine, `entry` is added to the end of the working
  484.         set's ``.entries`` (if it wasn't already present).
  485.  
  486.         `dist` is only added to the working set if it's for a project that
  487.         doesn't already have a distribution in the set.  If it's added, any
  488.         callbacks registered with the ``subscribe()`` method will be called.
  489.         """
  490.         if insert:
  491.             dist.insert_on(self.entries, entry)
  492.         
  493.         if entry is None:
  494.             entry = dist.location
  495.         
  496.         keys = self.entry_keys.setdefault(entry, [])
  497.         keys2 = self.entry_keys.setdefault(dist.location, [])
  498.         if dist.key in self.by_key:
  499.             return None
  500.         self.by_key[dist.key] = dist
  501.         if dist.key not in keys:
  502.             keys.append(dist.key)
  503.         
  504.         if dist.key not in keys2:
  505.             keys2.append(dist.key)
  506.         
  507.         self._added_new(dist)
  508.  
  509.     
  510.     def resolve(self, requirements, env = None, installer = None):
  511.         '''List all distributions needed to (recursively) meet `requirements`
  512.  
  513.         `requirements` must be a sequence of ``Requirement`` objects.  `env`,
  514.         if supplied, should be an ``Environment`` instance.  If
  515.         not supplied, it defaults to all distributions available within any
  516.         entry or distribution in the working set.  `installer`, if supplied,
  517.         will be invoked with each requirement that cannot be met by an
  518.         already-installed distribution; it should return a ``Distribution`` or
  519.         ``None``.
  520.         '''
  521.         requirements = list(requirements)[::-1]
  522.         processed = { }
  523.         best = { }
  524.         to_activate = []
  525.         while requirements:
  526.             req = requirements.pop(0)
  527.             if req in processed:
  528.                 continue
  529.             
  530.             dist = best.get(req.key)
  531.             if dist is None:
  532.                 dist = self.by_key.get(req.key)
  533.                 if dist is None:
  534.                     if env is None:
  535.                         env = Environment(self.entries)
  536.                     
  537.                     dist = best[req.key] = env.best_match(req, self, installer)
  538.                     if dist is None:
  539.                         raise DistributionNotFound(req)
  540.                     dist is None
  541.                 
  542.                 to_activate.append(dist)
  543.             
  544.             if dist not in req:
  545.                 raise VersionConflict(dist, req)
  546.             dist not in req
  547.             requirements.extend(dist.requires(req.extras)[::-1])
  548.             processed[req] = True
  549.         return to_activate
  550.  
  551.     
  552.     def find_plugins(self, plugin_env, full_env = None, installer = None, fallback = True):
  553.         '''Find all activatable distributions in `plugin_env`
  554.  
  555.         Example usage::
  556.  
  557.             distributions, errors = working_set.find_plugins(
  558.                 Environment(plugin_dirlist)
  559.             )
  560.             map(working_set.add, distributions)  # add plugins+libs to sys.path
  561.             print "Couldn\'t load", errors        # display errors
  562.  
  563.         The `plugin_env` should be an ``Environment`` instance that contains
  564.         only distributions that are in the project\'s "plugin directory" or
  565.         directories. The `full_env`, if supplied, should be an ``Environment``
  566.         contains all currently-available distributions.  If `full_env` is not
  567.         supplied, one is created automatically from the ``WorkingSet`` this
  568.         method is called on, which will typically mean that every directory on
  569.         ``sys.path`` will be scanned for distributions.
  570.  
  571.         `installer` is a standard installer callback as used by the
  572.         ``resolve()`` method. The `fallback` flag indicates whether we should
  573.         attempt to resolve older versions of a plugin if the newest version
  574.         cannot be resolved.
  575.  
  576.         This method returns a 2-tuple: (`distributions`, `error_info`), where
  577.         `distributions` is a list of the distributions found in `plugin_env`
  578.         that were loadable, along with any other distributions that are needed
  579.         to resolve their dependencies.  `error_info` is a dictionary mapping
  580.         unloadable plugin distributions to an exception instance describing the
  581.         error that occurred. Usually this will be a ``DistributionNotFound`` or
  582.         ``VersionConflict`` instance.
  583.         '''
  584.         plugin_projects = list(plugin_env)
  585.         plugin_projects.sort()
  586.         error_info = { }
  587.         distributions = { }
  588.         if full_env is None:
  589.             env = Environment(self.entries)
  590.             env += plugin_env
  591.         else:
  592.             env = full_env + plugin_env
  593.         shadow_set = self.__class__([])
  594.         map(shadow_set.add, self)
  595.         for project_name in plugin_projects:
  596.             for dist in plugin_env[project_name]:
  597.                 req = [
  598.                     dist.as_requirement()]
  599.                 
  600.                 try:
  601.                     resolvees = shadow_set.resolve(req, env, installer)
  602.                 except ResolutionError:
  603.                     v = None
  604.                     error_info[dist] = v
  605.                     if fallback:
  606.                         continue
  607.                     else:
  608.                         break
  609.                     fallback
  610.  
  611.                 map(shadow_set.add, resolvees)
  612.                 distributions.update(dict.fromkeys(resolvees))
  613.             
  614.         
  615.         distributions = list(distributions)
  616.         distributions.sort()
  617.         return (distributions, error_info)
  618.  
  619.     
  620.     def require(self, *requirements):
  621.         '''Ensure that distributions matching `requirements` are activated
  622.  
  623.         `requirements` must be a string or a (possibly-nested) sequence
  624.         thereof, specifying the distributions and versions required.  The
  625.         return value is a sequence of the distributions that needed to be
  626.         activated to fulfill the requirements; all relevant distributions are
  627.         included, even if they were already activated in this working set.
  628.         '''
  629.         needed = self.resolve(parse_requirements(requirements))
  630.         for dist in needed:
  631.             self.add(dist)
  632.         
  633.         return needed
  634.  
  635.     
  636.     def subscribe(self, callback):
  637.         '''Invoke `callback` for all distributions (including existing ones)'''
  638.         if callback in self.callbacks:
  639.             return None
  640.         self.callbacks.append(callback)
  641.         for dist in self:
  642.             callback(dist)
  643.         
  644.  
  645.     
  646.     def _added_new(self, dist):
  647.         for callback in self.callbacks:
  648.             callback(dist)
  649.         
  650.  
  651.  
  652.  
  653. class Environment(object):
  654.     '''Searchable snapshot of distributions on a search path'''
  655.     
  656.     def __init__(self, search_path = None, platform = get_supported_platform(), python = PY_MAJOR):
  657.         """Snapshot distributions available on a search path
  658.  
  659.         Any distributions found on `search_path` are added to the environment.
  660.         `search_path` should be a sequence of ``sys.path`` items.  If not
  661.         supplied, ``sys.path`` is used.
  662.  
  663.         `platform` is an optional string specifying the name of the platform
  664.         that platform-specific distributions must be compatible with.  If
  665.         unspecified, it defaults to the current platform.  `python` is an
  666.         optional string naming the desired version of Python (e.g. ``'2.4'``);
  667.         it defaults to the current version.
  668.  
  669.         You may explicitly set `platform` (and/or `python`) to ``None`` if you
  670.         wish to map *all* distributions, not just those compatible with the
  671.         running platform or Python version.
  672.         """
  673.         self._distmap = { }
  674.         self._cache = { }
  675.         self.platform = platform
  676.         self.python = python
  677.         self.scan(search_path)
  678.  
  679.     
  680.     def can_add(self, dist):
  681.         '''Is distribution `dist` acceptable for this environment?
  682.  
  683.         The distribution must match the platform and python version
  684.         requirements specified when this environment was created, or False
  685.         is returned.
  686.         '''
  687.         if self.python is None and dist.py_version is None or dist.py_version == self.python:
  688.             pass
  689.         return compatible_platforms(dist.platform, self.platform)
  690.  
  691.     
  692.     def remove(self, dist):
  693.         '''Remove `dist` from the environment'''
  694.         self._distmap[dist.key].remove(dist)
  695.  
  696.     
  697.     def scan(self, search_path = None):
  698.         '''Scan `search_path` for distributions usable in this environment
  699.  
  700.         Any distributions found are added to the environment.
  701.         `search_path` should be a sequence of ``sys.path`` items.  If not
  702.         supplied, ``sys.path`` is used.  Only distributions conforming to
  703.         the platform/python version defined at initialization are added.
  704.         '''
  705.         if search_path is None:
  706.             search_path = sys.path
  707.         
  708.         for item in search_path:
  709.             for dist in find_distributions(item):
  710.                 self.add(dist)
  711.             
  712.         
  713.  
  714.     
  715.     def __getitem__(self, project_name):
  716.         '''Return a newest-to-oldest list of distributions for `project_name`
  717.         '''
  718.         
  719.         try:
  720.             return self._cache[project_name]
  721.         except KeyError:
  722.             project_name = project_name.lower()
  723.             if project_name not in self._distmap:
  724.                 return []
  725.         except:
  726.             project_name not in self._distmap
  727.  
  728.         return self._cache[project_name]
  729.  
  730.     
  731.     def add(self, dist):
  732.         """Add `dist` if we ``can_add()`` it and it isn't already added"""
  733.         if self.can_add(dist) and dist.has_version():
  734.             dists = self._distmap.setdefault(dist.key, [])
  735.             if dist not in dists:
  736.                 dists.append(dist)
  737.                 if dist.key in self._cache:
  738.                     _sort_dists(self._cache[dist.key])
  739.                 
  740.             
  741.         
  742.  
  743.     
  744.     def best_match(self, req, working_set, installer = None):
  745.         """Find distribution best matching `req` and usable on `working_set`
  746.  
  747.         This calls the ``find(req)`` method of the `working_set` to see if a
  748.         suitable distribution is already active.  (This may raise
  749.         ``VersionConflict`` if an unsuitable version of the project is already
  750.         active in the specified `working_set`.)  If a suitable distribution
  751.         isn't active, this method returns the newest distribution in the
  752.         environment that meets the ``Requirement`` in `req`.  If no suitable
  753.         distribution is found, and `installer` is supplied, then the result of
  754.         calling the environment's ``obtain(req, installer)`` method will be
  755.         returned.
  756.         """
  757.         dist = working_set.find(req)
  758.         if dist is not None:
  759.             return dist
  760.         for dist in self[req.key]:
  761.             if dist in req:
  762.                 return dist
  763.         
  764.         return self.obtain(req, installer)
  765.  
  766.     
  767.     def obtain(self, requirement, installer = None):
  768.         '''Obtain a distribution matching `requirement` (e.g. via download)
  769.  
  770.         Obtain a distro that matches requirement (e.g. via download).  In the
  771.         base ``Environment`` class, this routine just returns
  772.         ``installer(requirement)``, unless `installer` is None, in which case
  773.         None is returned instead.  This method is a hook that allows subclasses
  774.         to attempt other ways of obtaining a distribution before falling back
  775.         to the `installer` argument.'''
  776.         if installer is not None:
  777.             return installer(requirement)
  778.  
  779.     
  780.     def __iter__(self):
  781.         '''Yield the unique project names of the available distributions'''
  782.         for key in self._distmap.keys():
  783.             if self[key]:
  784.                 yield key
  785.                 continue
  786.         
  787.  
  788.     
  789.     def __iadd__(self, other):
  790.         '''In-place addition of a distribution or environment'''
  791.         if isinstance(other, Distribution):
  792.             self.add(other)
  793.         elif isinstance(other, Environment):
  794.             for project in other:
  795.                 for dist in other[project]:
  796.                     self.add(dist)
  797.                 
  798.             
  799.         else:
  800.             raise TypeError("Can't add %r to environment" % (other,))
  801.         return isinstance(other, Distribution)
  802.  
  803.     
  804.     def __add__(self, other):
  805.         '''Add an environment or distribution to an environment'''
  806.         new = self.__class__([], platform = None, python = None)
  807.         for env in (self, other):
  808.             new += env
  809.         
  810.         return new
  811.  
  812.  
  813. AvailableDistributions = Environment
  814.  
  815. class ExtractionError(RuntimeError):
  816.     '''An error occurred extracting a resource
  817.  
  818.     The following attributes are available from instances of this exception:
  819.  
  820.     manager
  821.         The resource manager that raised this exception
  822.  
  823.     cache_path
  824.         The base directory for resource extraction
  825.  
  826.     original_error
  827.         The exception instance that caused extraction to fail
  828.     '''
  829.     pass
  830.  
  831.  
  832. class ResourceManager:
  833.     '''Manage resource extraction and packages'''
  834.     extraction_path = None
  835.     
  836.     def __init__(self):
  837.         self.cached_files = { }
  838.  
  839.     
  840.     def resource_exists(self, package_or_requirement, resource_name):
  841.         '''Does the named resource exist?'''
  842.         return get_provider(package_or_requirement).has_resource(resource_name)
  843.  
  844.     
  845.     def resource_isdir(self, package_or_requirement, resource_name):
  846.         '''Is the named resource an existing directory?'''
  847.         return get_provider(package_or_requirement).resource_isdir(resource_name)
  848.  
  849.     
  850.     def resource_filename(self, package_or_requirement, resource_name):
  851.         '''Return a true filesystem path for specified resource'''
  852.         return get_provider(package_or_requirement).get_resource_filename(self, resource_name)
  853.  
  854.     
  855.     def resource_stream(self, package_or_requirement, resource_name):
  856.         '''Return a readable file-like object for specified resource'''
  857.         return get_provider(package_or_requirement).get_resource_stream(self, resource_name)
  858.  
  859.     
  860.     def resource_string(self, package_or_requirement, resource_name):
  861.         '''Return specified resource as a string'''
  862.         return get_provider(package_or_requirement).get_resource_string(self, resource_name)
  863.  
  864.     
  865.     def resource_listdir(self, package_or_requirement, resource_name):
  866.         '''List the contents of the named resource directory'''
  867.         return get_provider(package_or_requirement).resource_listdir(resource_name)
  868.  
  869.     
  870.     def extraction_error(self):
  871.         '''Give an error message for problems extracting file(s)'''
  872.         old_exc = sys.exc_info()[1]
  873.         if not self.extraction_path:
  874.             pass
  875.         cache_path = get_default_cache()
  876.         err = ExtractionError("Can't extract file(s) to egg cache\n\nThe following error occurred while trying to extract file(s) to the Python egg\ncache:\n\n  %s\n\nThe Python egg cache directory is currently set to:\n\n  %s\n\nPerhaps your account does not have write access to this directory?  You can\nchange the cache directory by setting the PYTHON_EGG_CACHE environment\nvariable to point to an accessible directory.\n" % (old_exc, cache_path))
  877.         err.manager = self
  878.         err.cache_path = cache_path
  879.         err.original_error = old_exc
  880.         raise err
  881.  
  882.     
  883.     def get_cache_path(self, archive_name, names = ()):
  884.         '''Return absolute location in cache for `archive_name` and `names`
  885.  
  886.         The parent directory of the resulting path will be created if it does
  887.         not already exist.  `archive_name` should be the base filename of the
  888.         enclosing egg (which may not be the name of the enclosing zipfile!),
  889.         including its ".egg" extension.  `names`, if provided, should be a
  890.         sequence of path name parts "under" the egg\'s extraction location.
  891.  
  892.         This method should only be called by resource providers that need to
  893.         obtain an extraction location, and only for names they intend to
  894.         extract, as it tracks the generated names for possible cleanup later.
  895.         '''
  896.         if not self.extraction_path:
  897.             pass
  898.         extract_path = get_default_cache()
  899.         target_path = os.path.join(extract_path, archive_name + '-tmp', *names)
  900.         
  901.         try:
  902.             ensure_directory(target_path)
  903.         except:
  904.             self.extraction_error()
  905.  
  906.         self.cached_files[target_path] = 1
  907.         return target_path
  908.  
  909.     
  910.     def postprocess(self, tempname, filename):
  911.         """Perform any platform-specific postprocessing of `tempname`
  912.  
  913.         This is where Mac header rewrites should be done; other platforms don't
  914.         have anything special they should do.
  915.  
  916.         Resource providers should call this method ONLY after successfully
  917.         extracting a compressed resource.  They must NOT call it on resources
  918.         that are already in the filesystem.
  919.  
  920.         `tempname` is the current (temporary) name of the file, and `filename`
  921.         is the name it will be renamed to by the caller after this routine
  922.         returns.
  923.         """
  924.         if os.name == 'posix':
  925.             mode = (os.stat(tempname).st_mode | 365) & 4095
  926.             os.chmod(tempname, mode)
  927.         
  928.  
  929.     
  930.     def set_extraction_path(self, path):
  931.         """Set the base path where resources will be extracted to, if needed.
  932.  
  933.         If you do not call this routine before any extractions take place, the
  934.         path defaults to the return value of ``get_default_cache()``.  (Which
  935.         is based on the ``PYTHON_EGG_CACHE`` environment variable, with various
  936.         platform-specific fallbacks.  See that routine's documentation for more
  937.         details.)
  938.  
  939.         Resources are extracted to subdirectories of this path based upon
  940.         information given by the ``IResourceProvider``.  You may set this to a
  941.         temporary directory, but then you must call ``cleanup_resources()`` to
  942.         delete the extracted files when done.  There is no guarantee that
  943.         ``cleanup_resources()`` will be able to remove all extracted files.
  944.  
  945.         (Note: you may not change the extraction path for a given resource
  946.         manager once resources have been extracted, unless you first call
  947.         ``cleanup_resources()``.)
  948.         """
  949.         if self.cached_files:
  950.             raise ValueError("Can't change extraction path, files already extracted")
  951.         self.cached_files
  952.         self.extraction_path = path
  953.  
  954.     
  955.     def cleanup_resources(self, force = False):
  956.         '''
  957.         Delete all extracted resource files and directories, returning a list
  958.         of the file and directory names that could not be successfully removed.
  959.         This function does not have any concurrency protection, so it should
  960.         generally only be called when the extraction path is a temporary
  961.         directory exclusive to a single process.  This method is not
  962.         automatically called; you must call it explicitly or register it as an
  963.         ``atexit`` function if you wish to ensure cleanup of a temporary
  964.         directory used for extractions.
  965.         '''
  966.         pass
  967.  
  968.  
  969.  
  970. def get_default_cache():
  971.     '''Determine the default cache location
  972.  
  973.     This returns the ``PYTHON_EGG_CACHE`` environment variable, if set.
  974.     Otherwise, on Windows, it returns a "Python-Eggs" subdirectory of the
  975.     "Application Data" directory.  On all other systems, it\'s "~/.python-eggs".
  976.     '''
  977.     
  978.     try:
  979.         return os.environ['PYTHON_EGG_CACHE']
  980.     except KeyError:
  981.         pass
  982.  
  983.     if os.name != 'nt':
  984.         return os.path.expanduser('~/.python-eggs')
  985.     app_data = 'Application Data'
  986.     app_homes = [
  987.         (('APPDATA',), None),
  988.         (('USERPROFILE',), app_data),
  989.         (('HOMEDRIVE', 'HOMEPATH'), app_data),
  990.         (('HOMEPATH',), app_data),
  991.         (('HOME',), None),
  992.         (('WINDIR',), app_data)]
  993.     for keys, subdir in app_homes:
  994.         dirname = ''
  995.         for key in keys:
  996.             if key in os.environ:
  997.                 dirname = os.path.join(dirname, os.environ[key])
  998.                 continue
  999.             os.name != 'nt'
  1000.         elif subdir:
  1001.             dirname = os.path.join(dirname, subdir)
  1002.         
  1003.         return os.path.join(dirname, 'Python-Eggs')
  1004.     else:
  1005.         raise RuntimeError('Please set the PYTHON_EGG_CACHE enviroment variable')
  1006.  
  1007.  
  1008. def safe_name(name):
  1009.     """Convert an arbitrary string to a standard distribution name
  1010.  
  1011.     Any runs of non-alphanumeric/. characters are replaced with a single '-'.
  1012.     """
  1013.     return re.sub('[^A-Za-z0-9.]+', '-', name)
  1014.  
  1015.  
  1016. def safe_version(version):
  1017.     '''Convert an arbitrary string to a standard version string
  1018.  
  1019.     Spaces become dots, and all other non-alphanumeric characters become
  1020.     dashes, with runs of multiple dashes condensed to a single dash.
  1021.     '''
  1022.     version = version.replace(' ', '.')
  1023.     return re.sub('[^A-Za-z0-9.]+', '-', version)
  1024.  
  1025.  
  1026. def safe_extra(extra):
  1027.     """Convert an arbitrary string to a standard 'extra' name
  1028.  
  1029.     Any runs of non-alphanumeric characters are replaced with a single '_',
  1030.     and the result is always lowercased.
  1031.     """
  1032.     return re.sub('[^A-Za-z0-9.]+', '_', extra).lower()
  1033.  
  1034.  
  1035. def to_filename(name):
  1036.     """Convert a project or version name to its filename-escaped form
  1037.  
  1038.     Any '-' characters are currently replaced with '_'.
  1039.     """
  1040.     return name.replace('-', '_')
  1041.  
  1042.  
  1043. class NullProvider:
  1044.     '''Try to implement resources and metadata for arbitrary PEP 302 loaders'''
  1045.     egg_name = None
  1046.     egg_info = None
  1047.     loader = None
  1048.     
  1049.     def __init__(self, module):
  1050.         self.loader = getattr(module, '__loader__', None)
  1051.         self.module_path = os.path.dirname(getattr(module, '__file__', ''))
  1052.  
  1053.     
  1054.     def get_resource_filename(self, manager, resource_name):
  1055.         return self._fn(self.module_path, resource_name)
  1056.  
  1057.     
  1058.     def get_resource_stream(self, manager, resource_name):
  1059.         return StringIO(self.get_resource_string(manager, resource_name))
  1060.  
  1061.     
  1062.     def get_resource_string(self, manager, resource_name):
  1063.         return self._get(self._fn(self.module_path, resource_name))
  1064.  
  1065.     
  1066.     def has_resource(self, resource_name):
  1067.         return self._has(self._fn(self.module_path, resource_name))
  1068.  
  1069.     
  1070.     def has_metadata(self, name):
  1071.         if self.egg_info:
  1072.             pass
  1073.         return self._has(self._fn(self.egg_info, name))
  1074.  
  1075.     
  1076.     def get_metadata(self, name):
  1077.         if not self.egg_info:
  1078.             return ''
  1079.         return self._get(self._fn(self.egg_info, name))
  1080.  
  1081.     
  1082.     def get_metadata_lines(self, name):
  1083.         return yield_lines(self.get_metadata(name))
  1084.  
  1085.     
  1086.     def resource_isdir(self, resource_name):
  1087.         return self._isdir(self._fn(self.module_path, resource_name))
  1088.  
  1089.     
  1090.     def metadata_isdir(self, name):
  1091.         if self.egg_info:
  1092.             pass
  1093.         return self._isdir(self._fn(self.egg_info, name))
  1094.  
  1095.     
  1096.     def resource_listdir(self, resource_name):
  1097.         return self._listdir(self._fn(self.module_path, resource_name))
  1098.  
  1099.     
  1100.     def metadata_listdir(self, name):
  1101.         if self.egg_info:
  1102.             return self._listdir(self._fn(self.egg_info, name))
  1103.         return []
  1104.  
  1105.     
  1106.     def run_script(self, script_name, namespace):
  1107.         script = 'scripts/' + script_name
  1108.         if not self.has_metadata(script):
  1109.             raise ResolutionError('No script named %r' % script_name)
  1110.         self.has_metadata(script)
  1111.         script_text = self.get_metadata(script).replace('\r\n', '\n')
  1112.         script_text = script_text.replace('\r', '\n')
  1113.         script_filename = self._fn(self.egg_info, script)
  1114.         namespace['__file__'] = script_filename
  1115.         if os.path.exists(script_filename):
  1116.             execfile(script_filename, namespace, namespace)
  1117.         else:
  1118.             cache = cache
  1119.             import linecache
  1120.             cache[script_filename] = (len(script_text), 0, script_text.split('\n'), script_filename)
  1121.             script_code = compile(script_text, script_filename, 'exec')
  1122.             exec script_code in namespace, namespace
  1123.  
  1124.     
  1125.     def _has(self, path):
  1126.         raise NotImplementedError("Can't perform this operation for unregistered loader type")
  1127.  
  1128.     
  1129.     def _isdir(self, path):
  1130.         raise NotImplementedError("Can't perform this operation for unregistered loader type")
  1131.  
  1132.     
  1133.     def _listdir(self, path):
  1134.         raise NotImplementedError("Can't perform this operation for unregistered loader type")
  1135.  
  1136.     
  1137.     def _fn(self, base, resource_name):
  1138.         if resource_name:
  1139.             return os.path.join(base, *resource_name.split('/'))
  1140.         return base
  1141.  
  1142.     
  1143.     def _get(self, path):
  1144.         if hasattr(self.loader, 'get_data'):
  1145.             return self.loader.get_data(path)
  1146.         raise NotImplementedError("Can't perform this operation for loaders without 'get_data()'")
  1147.  
  1148.  
  1149. register_loader_type(object, NullProvider)
  1150.  
  1151. class EggProvider(NullProvider):
  1152.     '''Provider based on a virtual filesystem'''
  1153.     
  1154.     def __init__(self, module):
  1155.         NullProvider.__init__(self, module)
  1156.         self._setup_prefix()
  1157.  
  1158.     
  1159.     def _setup_prefix(self):
  1160.         path = self.module_path
  1161.         old = None
  1162.         while path != old:
  1163.             if path.lower().endswith('.egg'):
  1164.                 self.egg_name = os.path.basename(path)
  1165.                 self.egg_info = os.path.join(path, 'EGG-INFO')
  1166.                 self.egg_root = path
  1167.                 break
  1168.             
  1169.             old = path
  1170.             (path, base) = os.path.split(path)
  1171.  
  1172.  
  1173.  
  1174. class DefaultProvider(EggProvider):
  1175.     '''Provides access to package resources in the filesystem'''
  1176.     
  1177.     def _has(self, path):
  1178.         return os.path.exists(path)
  1179.  
  1180.     
  1181.     def _isdir(self, path):
  1182.         return os.path.isdir(path)
  1183.  
  1184.     
  1185.     def _listdir(self, path):
  1186.         return os.listdir(path)
  1187.  
  1188.     
  1189.     def get_resource_stream(self, manager, resource_name):
  1190.         return open(self._fn(self.module_path, resource_name), 'rb')
  1191.  
  1192.     
  1193.     def _get(self, path):
  1194.         stream = open(path, 'rb')
  1195.         
  1196.         try:
  1197.             return stream.read()
  1198.         finally:
  1199.             stream.close()
  1200.  
  1201.  
  1202.  
  1203. register_loader_type(type(None), DefaultProvider)
  1204.  
  1205. class EmptyProvider(NullProvider):
  1206.     '''Provider that returns nothing for all requests'''
  1207.     _isdir = _has = (lambda self, path: False)
  1208.     
  1209.     _get = lambda self, path: ''
  1210.     
  1211.     _listdir = lambda self, path: []
  1212.     module_path = None
  1213.     
  1214.     def __init__(self):
  1215.         pass
  1216.  
  1217.  
  1218. empty_provider = EmptyProvider()
  1219.  
  1220. class ZipProvider(EggProvider):
  1221.     '''Resource support for zips and eggs'''
  1222.     eagers = None
  1223.     
  1224.     def __init__(self, module):
  1225.         EggProvider.__init__(self, module)
  1226.         self.zipinfo = zipimport._zip_directory_cache[self.loader.archive]
  1227.         self.zip_pre = self.loader.archive + os.sep
  1228.  
  1229.     
  1230.     def _zipinfo_name(self, fspath):
  1231.         if fspath.startswith(self.zip_pre):
  1232.             return fspath[len(self.zip_pre):]
  1233.         raise AssertionError('%s is not a subpath of %s' % (fspath, self.zip_pre))
  1234.  
  1235.     
  1236.     def _parts(self, zip_path):
  1237.         fspath = self.zip_pre + zip_path
  1238.         if fspath.startswith(self.egg_root + os.sep):
  1239.             return fspath[len(self.egg_root) + 1:].split(os.sep)
  1240.         raise AssertionError('%s is not a subpath of %s' % (fspath, self.egg_root))
  1241.  
  1242.     
  1243.     def get_resource_filename(self, manager, resource_name):
  1244.         if not self.egg_name:
  1245.             raise NotImplementedError('resource_filename() only supported for .egg, not .zip')
  1246.         self.egg_name
  1247.         zip_path = self._resource_to_zip(resource_name)
  1248.         eagers = self._get_eager_resources()
  1249.         if '/'.join(self._parts(zip_path)) in eagers:
  1250.             for name in eagers:
  1251.                 self._extract_resource(manager, self._eager_to_zip(name))
  1252.             
  1253.         
  1254.         return self._extract_resource(manager, zip_path)
  1255.  
  1256.     
  1257.     def _extract_resource(self, manager, zip_path):
  1258.         if zip_path in self._index():
  1259.             for name in self._index()[zip_path]:
  1260.                 last = self._extract_resource(manager, os.path.join(zip_path, name))
  1261.             
  1262.             return os.path.dirname(last)
  1263.         zip_stat = self.zipinfo[zip_path]
  1264.         t = zip_stat[5]
  1265.         d = zip_stat[6]
  1266.         size = zip_stat[3]
  1267.         date_time = ((d >> 9) + 1980, d >> 5 & 15, d & 31, (t & 65535) >> 11, t >> 5 & 63, (t & 31) * 2, 0, 0, -1)
  1268.         timestamp = time.mktime(date_time)
  1269.         
  1270.         try:
  1271.             real_path = manager.get_cache_path(self.egg_name, self._parts(zip_path))
  1272.             (outf, tmpnam) = _mkstemp('.$extract', dir = os.path.dirname(real_path))
  1273.             os.write(outf, self.loader.get_data(zip_path))
  1274.             os.close(outf)
  1275.             utime(tmpnam, (timestamp, timestamp))
  1276.             manager.postprocess(tmpnam, real_path)
  1277.             
  1278.             try:
  1279.                 rename(tmpnam, real_path)
  1280.             except os.error:
  1281.                 None if os.path.isfile(real_path) else zip_path in self._index()
  1282.                 None if os.path.isfile(real_path) else zip_path in self._index()
  1283.                 raise 
  1284.             except:
  1285.                 None if os.path.isfile(real_path) else stat.st_mtime == timestamp
  1286.  
  1287.         except os.error:
  1288.             zip_path in self._index()
  1289.             zip_path in self._index()
  1290.             manager.extraction_error()
  1291.         except:
  1292.             zip_path in self._index()
  1293.  
  1294.         return real_path
  1295.  
  1296.     
  1297.     def _get_eager_resources(self):
  1298.         if self.eagers is None:
  1299.             eagers = []
  1300.             for name in ('native_libs.txt', 'eager_resources.txt'):
  1301.                 if self.has_metadata(name):
  1302.                     eagers.extend(self.get_metadata_lines(name))
  1303.                     continue
  1304.             
  1305.             self.eagers = eagers
  1306.         
  1307.         return self.eagers
  1308.  
  1309.     
  1310.     def _index(self):
  1311.         
  1312.         try:
  1313.             return self._dirindex
  1314.         except AttributeError:
  1315.             ind = { }
  1316.             for path in self.zipinfo:
  1317.                 parts = path.split(os.sep)
  1318.                 while parts:
  1319.                     parent = os.sep.join(parts[:-1])
  1320.                     if parent in ind:
  1321.                         ind[parent].append(parts[-1])
  1322.                         break
  1323.                         continue
  1324.                     ind[parent] = [
  1325.                         parts.pop()]
  1326.             
  1327.             self._dirindex = ind
  1328.             return ind
  1329.  
  1330.  
  1331.     
  1332.     def _has(self, fspath):
  1333.         zip_path = self._zipinfo_name(fspath)
  1334.         if not zip_path in self.zipinfo:
  1335.             pass
  1336.         return zip_path in self._index()
  1337.  
  1338.     
  1339.     def _isdir(self, fspath):
  1340.         return self._zipinfo_name(fspath) in self._index()
  1341.  
  1342.     
  1343.     def _listdir(self, fspath):
  1344.         return list(self._index().get(self._zipinfo_name(fspath), ()))
  1345.  
  1346.     
  1347.     def _eager_to_zip(self, resource_name):
  1348.         return self._zipinfo_name(self._fn(self.egg_root, resource_name))
  1349.  
  1350.     
  1351.     def _resource_to_zip(self, resource_name):
  1352.         return self._zipinfo_name(self._fn(self.module_path, resource_name))
  1353.  
  1354.  
  1355. register_loader_type(zipimport.zipimporter, ZipProvider)
  1356.  
  1357. class FileMetadata(EmptyProvider):
  1358.     '''Metadata handler for standalone PKG-INFO files
  1359.  
  1360.     Usage::
  1361.  
  1362.         metadata = FileMetadata("/path/to/PKG-INFO")
  1363.  
  1364.     This provider rejects all data and metadata requests except for PKG-INFO,
  1365.     which is treated as existing, and will be the contents of the file at
  1366.     the provided location.
  1367.     '''
  1368.     
  1369.     def __init__(self, path):
  1370.         self.path = path
  1371.  
  1372.     
  1373.     def has_metadata(self, name):
  1374.         return name == 'PKG-INFO'
  1375.  
  1376.     
  1377.     def get_metadata(self, name):
  1378.         if name == 'PKG-INFO':
  1379.             return open(self.path, 'rU').read()
  1380.         raise KeyError('No metadata except PKG-INFO is available')
  1381.  
  1382.     
  1383.     def get_metadata_lines(self, name):
  1384.         return yield_lines(self.get_metadata(name))
  1385.  
  1386.  
  1387.  
  1388. class PathMetadata(DefaultProvider):
  1389.     '''Metadata provider for egg directories
  1390.  
  1391.     Usage::
  1392.  
  1393.         # Development eggs:
  1394.  
  1395.         egg_info = "/path/to/PackageName.egg-info"
  1396.         base_dir = os.path.dirname(egg_info)
  1397.         metadata = PathMetadata(base_dir, egg_info)
  1398.         dist_name = os.path.splitext(os.path.basename(egg_info))[0]
  1399.         dist = Distribution(basedir,project_name=dist_name,metadata=metadata)
  1400.  
  1401.         # Unpacked egg directories:
  1402.  
  1403.         egg_path = "/path/to/PackageName-ver-pyver-etc.egg"
  1404.         metadata = PathMetadata(egg_path, os.path.join(egg_path,\'EGG-INFO\'))
  1405.         dist = Distribution.from_filename(egg_path, metadata=metadata)
  1406.     '''
  1407.     
  1408.     def __init__(self, path, egg_info):
  1409.         self.module_path = path
  1410.         self.egg_info = egg_info
  1411.  
  1412.  
  1413.  
  1414. class EggMetadata(ZipProvider):
  1415.     '''Metadata provider for .egg files'''
  1416.     
  1417.     def __init__(self, importer):
  1418.         '''Create a metadata provider from a zipimporter'''
  1419.         self.zipinfo = zipimport._zip_directory_cache[importer.archive]
  1420.         self.zip_pre = importer.archive + os.sep
  1421.         self.loader = importer
  1422.         if importer.prefix:
  1423.             self.module_path = os.path.join(importer.archive, importer.prefix)
  1424.         else:
  1425.             self.module_path = importer.archive
  1426.         self._setup_prefix()
  1427.  
  1428.  
  1429.  
  1430. class ImpWrapper:
  1431.     '''PEP 302 Importer that wraps Python\'s "normal" import algorithm'''
  1432.     
  1433.     def __init__(self, path = None):
  1434.         self.path = path
  1435.  
  1436.     
  1437.     def find_module(self, fullname, path = None):
  1438.         subname = fullname.split('.')[-1]
  1439.         if subname != fullname and self.path is None:
  1440.             return None
  1441.         if self.path is None:
  1442.             path = None
  1443.         else:
  1444.             path = [
  1445.                 self.path]
  1446.         
  1447.         try:
  1448.             (file, filename, etc) = imp.find_module(subname, path)
  1449.         except ImportError:
  1450.             return None
  1451.  
  1452.         return ImpLoader(file, filename, etc)
  1453.  
  1454.  
  1455.  
  1456. class ImpLoader:
  1457.     '''PEP 302 Loader that wraps Python\'s "normal" import algorithm'''
  1458.     
  1459.     def __init__(self, file, filename, etc):
  1460.         self.file = file
  1461.         self.filename = filename
  1462.         self.etc = etc
  1463.  
  1464.     
  1465.     def load_module(self, fullname):
  1466.         
  1467.         try:
  1468.             mod = imp.load_module(fullname, self.file, self.filename, self.etc)
  1469.         finally:
  1470.             if self.file:
  1471.                 self.file.close()
  1472.             
  1473.  
  1474.         return mod
  1475.  
  1476.  
  1477.  
  1478. def get_importer(path_item):
  1479.     '''Retrieve a PEP 302 "importer" for the given path item
  1480.  
  1481.     If there is no importer, this returns a wrapper around the builtin import
  1482.     machinery.  The returned importer is only cached if it was created by a
  1483.     path hook.
  1484.     '''
  1485.     
  1486.     try:
  1487.         importer = sys.path_importer_cache[path_item]
  1488.     except KeyError:
  1489.         for hook in sys.path_hooks:
  1490.             
  1491.             try:
  1492.                 importer = hook(path_item)
  1493.             except ImportError:
  1494.                 continue
  1495.  
  1496.         else:
  1497.             importer = None
  1498.  
  1499.     sys.path_importer_cache.setdefault(path_item, importer)
  1500.     if importer is None:
  1501.         
  1502.         try:
  1503.             importer = ImpWrapper(path_item)
  1504.         except ImportError:
  1505.             pass
  1506.         except:
  1507.             None<EXCEPTION MATCH>ImportError
  1508.         
  1509.  
  1510.     None<EXCEPTION MATCH>ImportError
  1511.     return importer
  1512.  
  1513.  
  1514. try:
  1515.     from pkgutil import get_importer, ImpImporter
  1516. except ImportError:
  1517.     pass
  1518.  
  1519. ImpWrapper = ImpImporter
  1520. del ImpLoader
  1521. del ImpImporter
  1522. _distribution_finders = { }
  1523.  
  1524. def register_finder(importer_type, distribution_finder):
  1525.     '''Register `distribution_finder` to find distributions in sys.path items
  1526.  
  1527.     `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
  1528.     handler), and `distribution_finder` is a callable that, passed a path
  1529.     item and the importer instance, yields ``Distribution`` instances found on
  1530.     that path item.  See ``pkg_resources.find_on_path`` for an example.'''
  1531.     _distribution_finders[importer_type] = distribution_finder
  1532.  
  1533.  
  1534. def find_distributions(path_item, only = False):
  1535.     '''Yield distributions accessible via `path_item`'''
  1536.     importer = get_importer(path_item)
  1537.     finder = _find_adapter(_distribution_finders, importer)
  1538.     return finder(importer, path_item, only)
  1539.  
  1540.  
  1541. def find_in_zip(importer, path_item, only = False):
  1542.     metadata = EggMetadata(importer)
  1543.     if metadata.has_metadata('PKG-INFO'):
  1544.         yield Distribution.from_filename(path_item, metadata = metadata)
  1545.     
  1546.     if only:
  1547.         return None
  1548.     for subitem in metadata.resource_listdir('/'):
  1549.         if subitem.endswith('.egg'):
  1550.             subpath = os.path.join(path_item, subitem)
  1551.             for dist in find_in_zip(zipimport.zipimporter(subpath), subpath):
  1552.                 yield dist
  1553.                 only
  1554.             
  1555.     
  1556.  
  1557. register_finder(zipimport.zipimporter, find_in_zip)
  1558.  
  1559. def StringIO(*args, **kw):
  1560.     '''Thunk to load the real StringIO on demand'''
  1561.     global StringIO, StringIO
  1562.     
  1563.     try:
  1564.         StringIO = StringIO
  1565.         import cStringIO
  1566.     except ImportError:
  1567.         StringIO = StringIO
  1568.         import StringIO
  1569.  
  1570.     return StringIO(*args, **kw)
  1571.  
  1572.  
  1573. def find_nothing(importer, path_item, only = False):
  1574.     return ()
  1575.  
  1576. register_finder(object, find_nothing)
  1577.  
  1578. def find_on_path(importer, path_item, only = False):
  1579.     '''Yield distributions accessible on a sys.path directory'''
  1580.     path_item = _normalize_cached(path_item)
  1581.     if os.path.isdir(path_item):
  1582.         if path_item.lower().endswith('.egg'):
  1583.             yield Distribution.from_filename(path_item, metadata = PathMetadata(path_item, os.path.join(path_item, 'EGG-INFO')))
  1584.         else:
  1585.             for entry in os.listdir(path_item):
  1586.                 lower = entry.lower()
  1587.                 if lower.endswith('.egg-info'):
  1588.                     fullpath = os.path.join(path_item, entry)
  1589.                     if os.path.isdir(fullpath):
  1590.                         metadata = PathMetadata(path_item, fullpath)
  1591.                     else:
  1592.                         metadata = FileMetadata(fullpath)
  1593.                     yield Distribution.from_location(path_item, entry, metadata, precedence = DEVELOP_DIST)
  1594.                     continue
  1595.                 if not only and lower.endswith('.egg'):
  1596.                     for dist in find_distributions(os.path.join(path_item, entry)):
  1597.                         yield dist
  1598.                     
  1599.                 if not only and lower.endswith('.egg-link'):
  1600.                     for line in file(os.path.join(path_item, entry)):
  1601.                         if not line.strip():
  1602.                             continue
  1603.                         
  1604.                         for item in find_distributions(os.path.join(path_item, line.rstrip())):
  1605.                             yield item
  1606.                         
  1607.                     
  1608.             
  1609.     
  1610.  
  1611. register_finder(ImpWrapper, find_on_path)
  1612. _namespace_handlers = { }
  1613. _namespace_packages = { }
  1614.  
  1615. def register_namespace_handler(importer_type, namespace_handler):
  1616.     '''Register `namespace_handler` to declare namespace packages
  1617.  
  1618.     `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
  1619.     handler), and `namespace_handler` is a callable like this::
  1620.  
  1621.         def namespace_handler(importer,path_entry,moduleName,module):
  1622.             # return a path_entry to use for child packages
  1623.  
  1624.     Namespace handlers are only called if the importer object has already
  1625.     agreed that it can handle the relevant path item, and they should only
  1626.     return a subpath if the module __path__ does not already contain an
  1627.     equivalent subpath.  For an example namespace handler, see
  1628.     ``pkg_resources.file_ns_handler``.
  1629.     '''
  1630.     _namespace_handlers[importer_type] = namespace_handler
  1631.  
  1632.  
  1633. def _handle_ns(packageName, path_item):
  1634.     '''Ensure that named package includes a subpath of path_item (if needed)'''
  1635.     importer = get_importer(path_item)
  1636.     if importer is None:
  1637.         return None
  1638.     loader = importer.find_module(packageName)
  1639.     if loader is None:
  1640.         return None
  1641.     module = sys.modules.get(packageName)
  1642.     if module is None:
  1643.         module.__path__ = []
  1644.         _set_parent_ns(packageName)
  1645.     elif not hasattr(module, '__path__'):
  1646.         raise TypeError('Not a package:', packageName)
  1647.     
  1648.     handler = _find_adapter(_namespace_handlers, importer)
  1649.     subpath = handler(importer, path_item, packageName, module)
  1650.     if subpath is not None:
  1651.         path = module.__path__
  1652.         path.append(subpath)
  1653.         loader.load_module(packageName)
  1654.         module.__path__ = path
  1655.     
  1656.     return subpath
  1657.  
  1658.  
  1659. def declare_namespace(packageName):
  1660.     """Declare that package 'packageName' is a namespace package"""
  1661.     imp.acquire_lock()
  1662.     
  1663.     try:
  1664.         if packageName in _namespace_packages:
  1665.             return None
  1666.         path = sys.path
  1667.         parent = None
  1668.         if '.' in packageName:
  1669.             parent = '.'.join(packageName.split('.')[:-1])
  1670.             declare_namespace(parent)
  1671.             __import__(parent)
  1672.             
  1673.             try:
  1674.                 path = sys.modules[parent].__path__
  1675.             except AttributeError:
  1676.                 packageName in _namespace_packages
  1677.                 packageName in _namespace_packages
  1678.                 raise TypeError('Not a package:', parent)
  1679.             except:
  1680.                 packageName in _namespace_packages<EXCEPTION MATCH>AttributeError
  1681.             
  1682.  
  1683.         packageName in _namespace_packages
  1684.         _namespace_packages.setdefault(parent, []).append(packageName)
  1685.         _namespace_packages.setdefault(packageName, [])
  1686.         for path_item in path:
  1687.             _handle_ns(packageName, path_item)
  1688.     finally:
  1689.         imp.release_lock()
  1690.  
  1691.  
  1692.  
  1693. def fixup_namespace_packages(path_item, parent = None):
  1694.     '''Ensure that previously-declared namespace packages include path_item'''
  1695.     imp.acquire_lock()
  1696.     
  1697.     try:
  1698.         for package in _namespace_packages.get(parent, ()):
  1699.             subpath = _handle_ns(package, path_item)
  1700.             if subpath:
  1701.                 fixup_namespace_packages(subpath, package)
  1702.                 continue
  1703.     finally:
  1704.         imp.release_lock()
  1705.  
  1706.  
  1707.  
  1708. def file_ns_handler(importer, path_item, packageName, module):
  1709.     '''Compute an ns-package subpath for a filesystem or zipfile importer'''
  1710.     subpath = os.path.join(path_item, packageName.split('.')[-1])
  1711.     normalized = _normalize_cached(subpath)
  1712.     for item in module.__path__:
  1713.         if _normalize_cached(item) == normalized:
  1714.             break
  1715.             continue
  1716.     else:
  1717.         return subpath
  1718.  
  1719. register_namespace_handler(ImpWrapper, file_ns_handler)
  1720. register_namespace_handler(zipimport.zipimporter, file_ns_handler)
  1721.  
  1722. def null_ns_handler(importer, path_item, packageName, module):
  1723.     pass
  1724.  
  1725. register_namespace_handler(object, null_ns_handler)
  1726.  
  1727. def normalize_path(filename):
  1728.     '''Normalize a file/dir name for comparison purposes'''
  1729.     return os.path.normcase(os.path.realpath(filename))
  1730.  
  1731.  
  1732. def _normalize_cached(filename, _cache = { }):
  1733.     
  1734.     try:
  1735.         return _cache[filename]
  1736.     except KeyError:
  1737.         _cache[filename] = result = normalize_path(filename)
  1738.         return result
  1739.  
  1740.  
  1741.  
  1742. def _set_parent_ns(packageName):
  1743.     parts = packageName.split('.')
  1744.     name = parts.pop()
  1745.     if parts:
  1746.         parent = '.'.join(parts)
  1747.         setattr(sys.modules[parent], name, sys.modules[packageName])
  1748.     
  1749.  
  1750.  
  1751. def yield_lines(strs):
  1752.     '''Yield non-empty/non-comment lines of a ``basestring`` or sequence'''
  1753.     if isinstance(strs, basestring):
  1754.         for s in strs.splitlines():
  1755.             s = s.strip()
  1756.             if s and not s.startswith('#'):
  1757.                 yield s
  1758.                 continue
  1759.         
  1760.     else:
  1761.         for ss in strs:
  1762.             for s in yield_lines(ss):
  1763.                 yield s
  1764.             
  1765.         
  1766.  
  1767. LINE_END = re.compile('\\s*(#.*)?$').match
  1768. CONTINUE = re.compile('\\s*\\\\\\s*(#.*)?$').match
  1769. DISTRO = re.compile('\\s*((\\w|[-.])+)').match
  1770. VERSION = re.compile('\\s*(<=?|>=?|==|!=)\\s*((\\w|[-.])+)').match
  1771. COMMA = re.compile('\\s*,').match
  1772. OBRACKET = re.compile('\\s*\\[').match
  1773. CBRACKET = re.compile('\\s*\\]').match
  1774. MODULE = re.compile('\\w+(\\.\\w+)*$').match
  1775. EGG_NAME = re.compile('(?P<name>[^-]+)( -(?P<ver>[^-]+) (-py(?P<pyver>[^-]+) (-(?P<plat>.+))? )? )?', re.VERBOSE | re.IGNORECASE).match
  1776. component_re = re.compile('(\\d+ | [a-z]+ | \\.| -)', re.VERBOSE)
  1777. replace = {
  1778.     'pre': 'c',
  1779.     'preview': 'c',
  1780.     '-': 'final-',
  1781.     'rc': 'c',
  1782.     'dev': '@' }.get
  1783.  
  1784. def _parse_version_parts(s):
  1785.     for part in component_re.split(s):
  1786.         part = replace(part, part)
  1787.         if not part or part == '.':
  1788.             continue
  1789.         
  1790.         if part[:1] in '0123456789':
  1791.             yield part.zfill(8)
  1792.             continue
  1793.         yield '*' + part
  1794.     
  1795.     yield '*final'
  1796.  
  1797.  
  1798. def parse_version(s):
  1799.     '''Convert a version string to a chronologically-sortable key
  1800.  
  1801.     This is a rough cross between distutils\' StrictVersion and LooseVersion;
  1802.     if you give it versions that would work with StrictVersion, then it behaves
  1803.     the same; otherwise it acts like a slightly-smarter LooseVersion. It is
  1804.     *possible* to create pathological version coding schemes that will fool
  1805.     this parser, but they should be very rare in practice.
  1806.  
  1807.     The returned value will be a tuple of strings.  Numeric portions of the
  1808.     version are padded to 8 digits so they will compare numerically, but
  1809.     without relying on how numbers compare relative to strings.  Dots are
  1810.     dropped, but dashes are retained.  Trailing zeros between alpha segments
  1811.     or dashes are suppressed, so that e.g. "2.4.0" is considered the same as
  1812.     "2.4". Alphanumeric parts are lower-cased.
  1813.  
  1814.     The algorithm assumes that strings like "-" and any alpha string that
  1815.     alphabetically follows "final"  represents a "patch level".  So, "2.4-1"
  1816.     is assumed to be a branch or patch of "2.4", and therefore "2.4.1" is
  1817.     considered newer than "2.4-1", which in turn is newer than "2.4".
  1818.  
  1819.     Strings like "a", "b", "c", "alpha", "beta", "candidate" and so on (that
  1820.     come before "final" alphabetically) are assumed to be pre-release versions,
  1821.     so that the version "2.4" is considered newer than "2.4a1".
  1822.  
  1823.     Finally, to handle miscellaneous cases, the strings "pre", "preview", and
  1824.     "rc" are treated as if they were "c", i.e. as though they were release
  1825.     candidates, and therefore are not as new as a version string that does not
  1826.     contain them, and "dev" is replaced with an \'@\' so that it sorts lower than
  1827.     than any other pre-release tag.
  1828.     '''
  1829.     parts = []
  1830.     for part in _parse_version_parts(s.lower()):
  1831.         if part.startswith('*'):
  1832.             if part < '*final':
  1833.                 while parts and parts[-1] == '*final-':
  1834.                     parts.pop()
  1835.             
  1836.             while parts and parts[-1] == '00000000':
  1837.                 parts.pop()
  1838.         
  1839.         parts.append(part)
  1840.     
  1841.     return tuple(parts)
  1842.  
  1843.  
  1844. class EntryPoint(object):
  1845.     '''Object representing an advertised importable object'''
  1846.     
  1847.     def __init__(self, name, module_name, attrs = (), extras = (), dist = None):
  1848.         if not MODULE(module_name):
  1849.             raise ValueError('Invalid module name', module_name)
  1850.         MODULE(module_name)
  1851.         self.name = name
  1852.         self.module_name = module_name
  1853.         self.attrs = tuple(attrs)
  1854.         self.extras = Requirement.parse('x[%s]' % ','.join(extras)).extras
  1855.         self.dist = dist
  1856.  
  1857.     
  1858.     def __str__(self):
  1859.         s = '%s = %s' % (self.name, self.module_name)
  1860.         if self.attrs:
  1861.             s += ':' + '.'.join(self.attrs)
  1862.         
  1863.         if self.extras:
  1864.             s += ' [%s]' % ','.join(self.extras)
  1865.         
  1866.         return s
  1867.  
  1868.     
  1869.     def __repr__(self):
  1870.         return 'EntryPoint.parse(%r)' % str(self)
  1871.  
  1872.     
  1873.     def load(self, require = True, env = None, installer = None):
  1874.         if require:
  1875.             self.require(env, installer)
  1876.         
  1877.         entry = __import__(self.module_name, globals(), globals(), [
  1878.             '__name__'])
  1879.         for attr in self.attrs:
  1880.             
  1881.             try:
  1882.                 entry = getattr(entry, attr)
  1883.             continue
  1884.             except AttributeError:
  1885.                 raise ImportError('%r has no %r attribute' % (entry, attr))
  1886.                 continue
  1887.             
  1888.  
  1889.         
  1890.         return entry
  1891.  
  1892.     
  1893.     def require(self, env = None, installer = None):
  1894.         if self.extras and not (self.dist):
  1895.             raise UnknownExtra("Can't require() without a distribution", self)
  1896.         not (self.dist)
  1897.         map(working_set.add, working_set.resolve(self.dist.requires(self.extras), env, installer))
  1898.  
  1899.     
  1900.     def parse(cls, src, dist = None):
  1901.         '''Parse a single entry point from string `src`
  1902.  
  1903.         Entry point syntax follows the form::
  1904.  
  1905.             name = some.module:some.attr [extra1,extra2]
  1906.  
  1907.         The entry name and module name are required, but the ``:attrs`` and
  1908.         ``[extras]`` parts are optional
  1909.         '''
  1910.         
  1911.         try:
  1912.             attrs = extras = ()
  1913.             (name, value) = src.split('=', 1)
  1914.             if '[' in value:
  1915.                 (value, extras) = value.split('[', 1)
  1916.                 req = Requirement.parse('x[' + extras)
  1917.                 if req.specs:
  1918.                     raise ValueError
  1919.                 req.specs
  1920.                 extras = req.extras
  1921.             
  1922.             if ':' in value:
  1923.                 (value, attrs) = value.split(':', 1)
  1924.                 if not MODULE(attrs.rstrip()):
  1925.                     raise ValueError
  1926.                 MODULE(attrs.rstrip())
  1927.                 attrs = attrs.rstrip().split('.')
  1928.         except ValueError:
  1929.             raise ValueError("EntryPoint must be in 'name=module:attrs [extras]' format", src)
  1930.  
  1931.         return cls(name.strip(), value.strip(), attrs, extras, dist)
  1932.  
  1933.     parse = classmethod(parse)
  1934.     
  1935.     def parse_group(cls, group, lines, dist = None):
  1936.         '''Parse an entry point group'''
  1937.         if not MODULE(group):
  1938.             raise ValueError('Invalid group name', group)
  1939.         MODULE(group)
  1940.         this = { }
  1941.         for line in yield_lines(lines):
  1942.             ep = cls.parse(line, dist)
  1943.             if ep.name in this:
  1944.                 raise ValueError('Duplicate entry point', group, ep.name)
  1945.             ep.name in this
  1946.             this[ep.name] = ep
  1947.         
  1948.         return this
  1949.  
  1950.     parse_group = classmethod(parse_group)
  1951.     
  1952.     def parse_map(cls, data, dist = None):
  1953.         '''Parse a map of entry point groups'''
  1954.         if isinstance(data, dict):
  1955.             data = data.items()
  1956.         else:
  1957.             data = split_sections(data)
  1958.         maps = { }
  1959.         for group, lines in data:
  1960.             if group is None:
  1961.                 if not lines:
  1962.                     continue
  1963.                 
  1964.                 raise ValueError('Entry points must be listed in groups')
  1965.             group is None
  1966.             group = group.strip()
  1967.             if group in maps:
  1968.                 raise ValueError('Duplicate group name', group)
  1969.             group in maps
  1970.             maps[group] = cls.parse_group(group, lines, dist)
  1971.         
  1972.         return maps
  1973.  
  1974.     parse_map = classmethod(parse_map)
  1975.  
  1976.  
  1977. class Distribution(object):
  1978.     '''Wrap an actual or potential sys.path entry w/metadata'''
  1979.     
  1980.     def __init__(self, location = None, metadata = None, project_name = None, version = None, py_version = PY_MAJOR, platform = None, precedence = EGG_DIST):
  1981.         if not project_name:
  1982.             pass
  1983.         self.project_name = safe_name('Unknown')
  1984.         if version is not None:
  1985.             self._version = safe_version(version)
  1986.         
  1987.         self.py_version = py_version
  1988.         self.platform = platform
  1989.         self.location = location
  1990.         self.precedence = precedence
  1991.         if not metadata:
  1992.             pass
  1993.         self._provider = empty_provider
  1994.  
  1995.     
  1996.     def from_location(cls, location, basename, metadata = None, **kw):
  1997.         (project_name, version, py_version, platform) = [
  1998.             None] * 4
  1999.         (basename, ext) = os.path.splitext(basename)
  2000.         if ext.lower() in ('.egg', '.egg-info'):
  2001.             match = EGG_NAME(basename)
  2002.             if match:
  2003.                 (project_name, version, py_version, platform) = match.group('name', 'ver', 'pyver', 'plat')
  2004.             
  2005.         
  2006.         return cls(location, metadata, project_name = project_name, version = version, py_version = py_version, platform = platform, **kw)
  2007.  
  2008.     from_location = classmethod(from_location)
  2009.     hashcmp = property((lambda self: if not self.location:
  2010. pass(getattr(self, 'parsed_version', ()), self.precedence, self.key, -len(''), self.location, self.py_version, self.platform)))
  2011.     
  2012.     def __cmp__(self, other):
  2013.         return cmp(self.hashcmp, other)
  2014.  
  2015.     
  2016.     def __hash__(self):
  2017.         return hash(self.hashcmp)
  2018.  
  2019.     
  2020.     def key(self):
  2021.         
  2022.         try:
  2023.             return self._key
  2024.         except AttributeError:
  2025.             self._key = key = self.project_name.lower()
  2026.             return key
  2027.  
  2028.  
  2029.     key = property(key)
  2030.     
  2031.     def parsed_version(self):
  2032.         
  2033.         try:
  2034.             return self._parsed_version
  2035.         except AttributeError:
  2036.             self._parsed_version = pv = parse_version(self.version)
  2037.             return pv
  2038.  
  2039.  
  2040.     parsed_version = property(parsed_version)
  2041.     
  2042.     def version(self):
  2043.         
  2044.         try:
  2045.             return self._version
  2046.         except AttributeError:
  2047.             for line in self._get_metadata('PKG-INFO'):
  2048.                 if line.lower().startswith('version:'):
  2049.                     self._version = safe_version(line.split(':', 1)[1].strip())
  2050.                     return self._version
  2051.             else:
  2052.                 raise ValueError("Missing 'Version:' header and/or PKG-INFO file", self)
  2053.             line.lower().startswith('version:')
  2054.  
  2055.  
  2056.     version = property(version)
  2057.     
  2058.     def _dep_map(self):
  2059.         
  2060.         try:
  2061.             return self._Distribution__dep_map
  2062.         except AttributeError:
  2063.             dm = self._Distribution__dep_map = {
  2064.                 None: [] }
  2065.             for name in ('requires.txt', 'depends.txt'):
  2066.                 for extra, reqs in split_sections(self._get_metadata(name)):
  2067.                     if extra:
  2068.                         extra = safe_extra(extra)
  2069.                     
  2070.                     dm.setdefault(extra, []).extend(parse_requirements(reqs))
  2071.                 
  2072.             
  2073.             return dm
  2074.  
  2075.  
  2076.     _dep_map = property(_dep_map)
  2077.     
  2078.     def requires(self, extras = ()):
  2079.         '''List of Requirements needed for this distro if `extras` are used'''
  2080.         dm = self._dep_map
  2081.         deps = []
  2082.         deps.extend(dm.get(None, ()))
  2083.         for ext in extras:
  2084.             
  2085.             try:
  2086.                 deps.extend(dm[safe_extra(ext)])
  2087.             continue
  2088.             except KeyError:
  2089.                 raise UnknownExtra('%s has no such extra feature %r' % (self, ext))
  2090.                 continue
  2091.             
  2092.  
  2093.         
  2094.         return deps
  2095.  
  2096.     
  2097.     def _get_metadata(self, name):
  2098.         if self.has_metadata(name):
  2099.             for line in self.get_metadata_lines(name):
  2100.                 yield line
  2101.             
  2102.         
  2103.  
  2104.     
  2105.     def activate(self, path = None):
  2106.         '''Ensure distribution is importable on `path` (default=sys.path)'''
  2107.         if path is None:
  2108.             path = sys.path
  2109.         
  2110.         self.insert_on(path)
  2111.         if path is sys.path:
  2112.             fixup_namespace_packages(self.location)
  2113.             map(declare_namespace, self._get_metadata('namespace_packages.txt'))
  2114.         
  2115.  
  2116.     
  2117.     def egg_name(self):
  2118.         """Return what this distribution's standard .egg filename should be"""
  2119.         if not self.py_version:
  2120.             pass
  2121.         filename = '%s-%s-py%s' % (to_filename(self.project_name), to_filename(self.version), PY_MAJOR)
  2122.         if self.platform:
  2123.             filename += '-' + self.platform
  2124.         
  2125.         return filename
  2126.  
  2127.     
  2128.     def __repr__(self):
  2129.         if self.location:
  2130.             return '%s (%s)' % (self, self.location)
  2131.         return str(self)
  2132.  
  2133.     
  2134.     def __str__(self):
  2135.         
  2136.         try:
  2137.             version = getattr(self, 'version', None)
  2138.         except ValueError:
  2139.             version = None
  2140.  
  2141.         if not version:
  2142.             pass
  2143.         version = '[unknown version]'
  2144.         return '%s %s' % (self.project_name, version)
  2145.  
  2146.     
  2147.     def __getattr__(self, attr):
  2148.         '''Delegate all unrecognized public attributes to .metadata provider'''
  2149.         if attr.startswith('_'):
  2150.             raise AttributeError, attr
  2151.         attr.startswith('_')
  2152.         return getattr(self._provider, attr)
  2153.  
  2154.     
  2155.     def from_filename(cls, filename, metadata = None, **kw):
  2156.         return cls.from_location(_normalize_cached(filename), os.path.basename(filename), metadata, **kw)
  2157.  
  2158.     from_filename = classmethod(from_filename)
  2159.     
  2160.     def as_requirement(self):
  2161.         '''Return a ``Requirement`` that matches this distribution exactly'''
  2162.         return Requirement.parse('%s==%s' % (self.project_name, self.version))
  2163.  
  2164.     
  2165.     def load_entry_point(self, group, name):
  2166.         '''Return the `name` entry point of `group` or raise ImportError'''
  2167.         ep = self.get_entry_info(group, name)
  2168.         if ep is None:
  2169.             raise ImportError('Entry point %r not found' % ((group, name),))
  2170.         ep is None
  2171.         return ep.load()
  2172.  
  2173.     
  2174.     def get_entry_map(self, group = None):
  2175.         '''Return the entry point map for `group`, or the full entry map'''
  2176.         
  2177.         try:
  2178.             ep_map = self._ep_map
  2179.         except AttributeError:
  2180.             ep_map = self._ep_map = EntryPoint.parse_map(self._get_metadata('entry_points.txt'), self)
  2181.  
  2182.         if group is not None:
  2183.             return ep_map.get(group, { })
  2184.         return ep_map
  2185.  
  2186.     
  2187.     def get_entry_info(self, group, name):
  2188.         '''Return the EntryPoint object for `group`+`name`, or ``None``'''
  2189.         return self.get_entry_map(group).get(name)
  2190.  
  2191.     
  2192.     def insert_on(self, path, loc = None):
  2193.         '''Insert self.location in path before its nearest parent directory'''
  2194.         if not loc:
  2195.             pass
  2196.         loc = self.location
  2197.         if not loc:
  2198.             return None
  2199.         if path is sys.path:
  2200.             self.check_version_conflict()
  2201.         
  2202.         nloc = _normalize_cached(loc)
  2203.         bdir = os.path.dirname(nloc)
  2204.         npath = map(_normalize_cached, path)
  2205.         bp = None
  2206.         for p, item in enumerate(npath):
  2207.             if item == nloc:
  2208.                 break
  2209.                 continue
  2210.             if item == bdir and self.precedence == EGG_DIST:
  2211.                 path.insert(p, loc)
  2212.                 npath.insert(p, nloc)
  2213.                 break
  2214.                 continue
  2215.         else:
  2216.             return None
  2217.         
  2218.         try:
  2219.             np = npath.index(nloc, p + 1)
  2220.         except ValueError:
  2221.             break
  2222.             continue
  2223.  
  2224.         del npath[np]
  2225.         del path[np]
  2226.         p = np
  2227.         continue
  2228.  
  2229.     
  2230.     def check_version_conflict(self):
  2231.         if self.key == 'setuptools':
  2232.             return None
  2233.         nsp = dict.fromkeys(self._get_metadata('namespace_packages.txt'))
  2234.         loc = normalize_path(self.location)
  2235.         for modname in self._get_metadata('top_level.txt'):
  2236.             if modname not in sys.modules and modname in nsp or modname in _namespace_packages:
  2237.                 continue
  2238.             
  2239.             fn = getattr(sys.modules[modname], '__file__', None)
  2240.             if fn and normalize_path(fn).startswith(loc):
  2241.                 continue
  2242.             
  2243.             issue_warning('Module %s was already imported from %s, but %s is being added to sys.path' % (modname, fn, self.location))
  2244.         
  2245.  
  2246.     
  2247.     def has_version(self):
  2248.         
  2249.         try:
  2250.             self.version
  2251.         except ValueError:
  2252.             issue_warning('Unbuilt egg for ' + repr(self))
  2253.             return False
  2254.  
  2255.         return True
  2256.  
  2257.     
  2258.     def clone(self, **kw):
  2259.         '''Copy this distribution, substituting in any changed keyword args'''
  2260.         for attr in ('project_name', 'version', 'py_version', 'platform', 'location', 'precedence'):
  2261.             kw.setdefault(attr, getattr(self, attr, None))
  2262.         
  2263.         kw.setdefault('metadata', self._provider)
  2264.         return self.__class__(**kw)
  2265.  
  2266.     
  2267.     def extras(self):
  2268.         return _[1]
  2269.  
  2270.     extras = property(extras)
  2271.  
  2272.  
  2273. def issue_warning(*args, **kw):
  2274.     level = 1
  2275.     g = globals()
  2276.     
  2277.     try:
  2278.         while sys._getframe(level).f_globals is g:
  2279.             level += 1
  2280.     except ValueError:
  2281.         pass
  2282.  
  2283.     warn = warn
  2284.     import warnings
  2285.     warn(stacklevel = level + 1, *args, **kw)
  2286.  
  2287.  
  2288. def parse_requirements(strs):
  2289.     '''Yield ``Requirement`` objects for each specification in `strs`
  2290.  
  2291.     `strs` must be an instance of ``basestring``, or a (possibly-nested)
  2292.     iterable thereof.
  2293.     '''
  2294.     lines = iter(yield_lines(strs))
  2295.     
  2296.     def scan_list(ITEM, TERMINATOR, line, p, groups, item_name):
  2297.         items = []
  2298.         while not TERMINATOR(line, p):
  2299.             if CONTINUE(line, p):
  2300.                 
  2301.                 try:
  2302.                     line = lines.next()
  2303.                     p = 0
  2304.                 except StopIteration:
  2305.                     raise ValueError('\\ must not appear on the last nonblank line')
  2306.                 except:
  2307.                     None<EXCEPTION MATCH>StopIteration
  2308.                 
  2309.  
  2310.             None<EXCEPTION MATCH>StopIteration
  2311.             match = ITEM(line, p)
  2312.             if not match:
  2313.                 raise ValueError('Expected ' + item_name + ' in', line, 'at', line[p:])
  2314.             match
  2315.             items.append(match.group(*groups))
  2316.             p = match.end()
  2317.             match = COMMA(line, p)
  2318.             if match:
  2319.                 p = match.end()
  2320.                 continue
  2321.             if not TERMINATOR(line, p):
  2322.                 raise ValueError("Expected ',' or end-of-list in", line, 'at', line[p:])
  2323.             TERMINATOR(line, p)
  2324.         match = TERMINATOR(line, p)
  2325.         if match:
  2326.             p = match.end()
  2327.         
  2328.         return (line, p, items)
  2329.  
  2330.     for line in lines:
  2331.         match = DISTRO(line)
  2332.         if not match:
  2333.             raise ValueError('Missing distribution spec', line)
  2334.         match
  2335.         project_name = match.group(1)
  2336.         p = match.end()
  2337.         extras = []
  2338.         match = OBRACKET(line, p)
  2339.         if match:
  2340.             p = match.end()
  2341.             (line, p, extras) = scan_list(DISTRO, CBRACKET, line, p, (1,), "'extra' name")
  2342.         
  2343.         (line, p, specs) = scan_list(VERSION, LINE_END, line, p, (1, 2), 'version spec')
  2344.         specs = [ (op, safe_version(val)) for op, val in specs ]
  2345.         yield Requirement(project_name, specs, extras)
  2346.         []
  2347.     
  2348.  
  2349.  
  2350. def _sort_dists(dists):
  2351.     tmp = [ (dist.hashcmp, dist) for dist in dists ]
  2352.     tmp.sort()
  2353.     dists[::-1] = [ d for hc, d in tmp ]
  2354.  
  2355.  
  2356. class Requirement:
  2357.     
  2358.     def __init__(self, project_name, specs, extras):
  2359.         '''DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!'''
  2360.         self.unsafe_name = project_name
  2361.         project_name = safe_name(project_name)
  2362.         self.project_name = project_name
  2363.         self.key = project_name.lower()
  2364.         index = [ (parse_version(v), state_machine[op], op, v) for op, v in specs ]
  2365.         index.sort()
  2366.         self.specs = [ (op, ver) for parsed, trans, op, ver in index ]
  2367.         self.index = index
  2368.         self.extras = tuple(map(safe_extra, extras))
  2369.         self.hashCmp = ([], []([ (op, parsed) for parsed, trans, op, ver in index ]), frozenset(self.extras))
  2370.         self._Requirement__hash = hash(self.hashCmp)
  2371.  
  2372.     
  2373.     def __str__(self):
  2374.         specs = []([ ''.join(s) for s in self.specs ])
  2375.         extras = ','.join(self.extras)
  2376.         return '%s%s%s' % (self.project_name, extras, specs)
  2377.  
  2378.     
  2379.     def __eq__(self, other):
  2380.         if isinstance(other, Requirement):
  2381.             pass
  2382.         return self.hashCmp == other.hashCmp
  2383.  
  2384.     
  2385.     def __contains__(self, item):
  2386.         if isinstance(item, Distribution):
  2387.             if item.key != self.key:
  2388.                 return False
  2389.             if self.index:
  2390.                 item = item.parsed_version
  2391.             
  2392.         elif isinstance(item, basestring):
  2393.             item = parse_version(item)
  2394.         
  2395.         last = None
  2396.         for parsed, trans, op, ver in self.index:
  2397.             action = trans[cmp(item, parsed)]
  2398.             if action == 'F':
  2399.                 return False
  2400.             if action == 'T':
  2401.                 return True
  2402.             if action == '+':
  2403.                 last = True
  2404.                 continue
  2405.             action == 'T'
  2406.             if action == '-' or last is None:
  2407.                 last = False
  2408.                 continue
  2409.             action == 'F'
  2410.         
  2411.         if last is None:
  2412.             last = True
  2413.         
  2414.         return last
  2415.  
  2416.     
  2417.     def __hash__(self):
  2418.         return self._Requirement__hash
  2419.  
  2420.     
  2421.     def __repr__(self):
  2422.         return 'Requirement.parse(%r)' % str(self)
  2423.  
  2424.     
  2425.     def parse(s):
  2426.         reqs = list(parse_requirements(s))
  2427.         if reqs:
  2428.             if len(reqs) == 1:
  2429.                 return reqs[0]
  2430.             raise ValueError('Expected only one requirement', s)
  2431.         reqs
  2432.         raise ValueError('No requirements found', s)
  2433.  
  2434.     parse = staticmethod(parse)
  2435.  
  2436. state_machine = {
  2437.     '<': '--T',
  2438.     '<=': 'T-T',
  2439.     '>': 'F+F',
  2440.     '>=': 'T+F',
  2441.     '==': 'T..',
  2442.     '!=': 'F++' }
  2443.  
  2444. def _get_mro(cls):
  2445.     '''Get an mro for a type or classic class'''
  2446.     if not isinstance(cls, type):
  2447.         
  2448.         class cls(cls, object):
  2449.             pass
  2450.  
  2451.         return cls.__mro__[1:]
  2452.     return cls.__mro__
  2453.  
  2454.  
  2455. def _find_adapter(registry, ob):
  2456.     '''Return an adapter factory for `ob` from `registry`'''
  2457.     for t in _get_mro(getattr(ob, '__class__', type(ob))):
  2458.         if t in registry:
  2459.             return registry[t]
  2460.     
  2461.  
  2462.  
  2463. def ensure_directory(path):
  2464.     '''Ensure that the parent directory of `path` exists'''
  2465.     dirname = os.path.dirname(path)
  2466.     if not os.path.isdir(dirname):
  2467.         os.makedirs(dirname)
  2468.     
  2469.  
  2470.  
  2471. def split_sections(s):
  2472.     '''Split a string or iterable thereof into (section,content) pairs
  2473.  
  2474.     Each ``section`` is a stripped version of the section header ("[section]")
  2475.     and each ``content`` is a list of stripped lines excluding blank lines and
  2476.     comment-only lines.  If there are any such lines before the first section
  2477.     header, they\'re returned in a first ``section`` of ``None``.
  2478.     '''
  2479.     section = None
  2480.     content = []
  2481.     for line in yield_lines(s):
  2482.         if line.startswith('['):
  2483.             if line.endswith(']'):
  2484.                 if section or content:
  2485.                     yield (section, content)
  2486.                 
  2487.                 section = line[1:-1].strip()
  2488.                 content = []
  2489.             else:
  2490.                 raise ValueError('Invalid section heading', line)
  2491.         line.endswith(']')
  2492.         content.append(line)
  2493.     
  2494.     yield (section, content)
  2495.  
  2496.  
  2497. def _mkstemp(*args, **kw):
  2498.     mkstemp = mkstemp
  2499.     import tempfile
  2500.     old_open = os.open
  2501.     
  2502.     try:
  2503.         os.open = os_open
  2504.         return mkstemp(*args, **kw)
  2505.     finally:
  2506.         os.open = old_open
  2507.  
  2508.  
  2509. _manager = ResourceManager()
  2510.  
  2511. def _initialize(g):
  2512.     for name in dir(_manager):
  2513.         if not name.startswith('_'):
  2514.             g[name] = getattr(_manager, name)
  2515.             continue
  2516.     
  2517.  
  2518. _initialize(globals())
  2519. working_set = WorkingSet()
  2520.  
  2521. try:
  2522.     from __main__ import __requires__
  2523. except ImportError:
  2524.     pass
  2525.  
  2526.  
  2527. try:
  2528.     working_set.require(__requires__)
  2529. except VersionConflict:
  2530.     working_set = WorkingSet([])
  2531.     for dist in working_set.resolve(parse_requirements(__requires__), Environment()):
  2532.         working_set.add(dist)
  2533.     
  2534.     for entry in sys.path:
  2535.         if entry not in working_set.entries:
  2536.             working_set.add_entry(entry)
  2537.         
  2538.     
  2539.     sys.path[:] = working_set.entries
  2540.  
  2541. require = working_set.require
  2542. iter_entry_points = working_set.iter_entry_points
  2543. add_activation_listener = working_set.subscribe
  2544. run_script = working_set.run_script
  2545. run_main = run_script
  2546. add_activation_listener((lambda dist: dist.activate()))
  2547. working_set.entries = []
  2548. map(working_set.add_entry, sys.path)
  2549.